<?php
/*
 * 佣金/奖金交换
 */
namespace Mobile\Controller;

use Mobile\Model\moneylogModel;
use Mobile\Model\tmpmsgModel;

class TransfersprizemoneyController extends BaseController {
    
    public $tmpmsgModel;
    public $moneylogModel;
    public $smscodeModel;

    public function __construct() {
        parent::__construct();
        $this->moneylogModel = new moneylogModel();
        $this->tmpmsgModel = new tmpmsgModel();
        $this->smscodeModel = new \Mobile\Model\smscodeModel();
    }
    
    /*
     * 佣金交换
     */
    public function index(){
        $seo_data = array(
            "title" => C('YONGJIN_NAME')."交换",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
    
        $share_data = array(
            "title" => C('YONGJIN_NAME')."交换",
        );
        $this->setShare($share_data);
    
        $this->display();
    }
    
    
    /*
     * 检查信息是否合法
     */
    protected function _check_data(){
        
        //过滤数据
        $allow = array(
            "message","to_uid","to_mobile","prize_money",'smscode','code_id','mobile'
        );
        $must = array("prize_money","to_uid");
        $data = param_filter($_POST,$allow,$must);
        
        
        //对方UID
        if(!$data['to_uid']){
            return_json(1,"请填写用户编号或用户手机账号");
        }
        
        //对方手机号
        if($data['to_mobile'] != ''){
            $chekc_mobile = check_mobile($data['to_mobile']);//检查手机号
            if(!$chekc_mobile){
                return_json(1,"对方手机号填写错误,请检查");
            }
        }
        
        $userinfo = $this->_getfriend($data['to_uid']);//获取对方信息
        $data['shou_userinfo'] = $userinfo;
        
        //交换金额
        $money = $data['prize_money'];
        if($money<=0){
            return_json(1,"交换金额必须大于0");
        }
        
        if($money>50000){
            return_json(1,"交换金额不能大于50000");
        }
        
        //获取我的信息
        $myinfo = $this->getMemberInfobyUid($this->uid);
        
        
        if($money>$myinfo['prize_money']){
            return_json(1,"你的".C('YONGJIN_NAME')."余额为:".$myinfo['prize_money'].",不足以进行此次交换,请修改交换金额");
        }
        
        //判断用户状态
        if($myinfo['status'] != 1){
            return_json(1,"你的账号状态异常,存在安全隐患,已被冻结,请联系客服处理");
        }
        
        
        return $data;
    }

    
    /*
     * 转佣金ajax操作
     */
    public function tfmoneyajax(){
    
        //获取数据
        $data = $this->_check_data();
        
        $this->_checkCode($data);
    
        //可以交换
        //1.从我的账户扣除金额,并给对方加上金额
        $where_me = array(
            "uid" => $this->uid
        );
        $res = $this->memberModel->where($where_me)->setDec('prize_money',$data['prize_money']);//把金额从转款人账户扣除
        if(!$res){
            return_json(1,"网络异常,交换失败,请重试");
        }
        
        //写我的交换日志
        $myinfo = $this->getMemberInfobyUid($this->uid);
    
        $to_nickname = $data['shou_userinfo']['realname'] ? $data['shou_userinfo']['realname'] : $data['shou_userinfo']['nickname'];//收款人真实姓名
        $my_nickname = $myinfo['realname'] ? $myinfo['realname'] : $myinfo['nickname'];//转款人真实姓名
        $content = "[".C("YONGJIN_NAME")."转出]收款人:".$to_nickname."(ID:".$data['shou_userinfo']['uid'].") ".$data['message'];
    
        //写我的流水
        $log_id = $this->_tfmoney_log($this->uid,$my_nickname,$data['shou_userinfo']['uid'],$to_nickname,$content,$data['prize_money'],0);
        //给我发送模板消息
        $header = "类型：".C("YONGJIN_NAME")."转出".'\\n'."收款人:".$data['shou_userinfo']['nickname']."(ID:".$data['shou_userinfo']['uid'].')\\n'."交换金额:".$data['prize_money'].'\\n'."备注消息:".$data['message'];
        $this->_tfmoney_msg($log_id,$myinfo,$data['prize_money'],$header);//发送模板消息
        
        //给对方写流水
        //给对方加上
        $where_to = array(
            "uid" => $data['shou_userinfo']['uid']
        );
        $res = $this->memberModel->where($where_to)->setInc('prize_money',$data['prize_money']);//把金额加入到收款人账户
        if(!$res){
            return false;
        }

        $content = "[".C("YONGJIN_NAME")."转入]转款人:".$my_nickname."(ID:".$this->uid.") ".$data['message'];
        $log_id = $this->_tfmoney_log($data['shou_userinfo']['uid'],$to_nickname,$this->uid,$my_nickname,$content,$data['prize_money'],1);
        $header = "类型：".C("YONGJIN_NAME")."转入".'\\n'."交换人:".$my_nickname."(ID:".$this->uid.')\\n'."交换金额:".$data['prize_money'].'\\n'."备注消息:".$data['message'];
        
        $this->_tfmoney_msg($log_id,$data['shou_userinfo'],$data['prize_money'],$header);//发送收方模板消息

        //发送手机短信  $to_mobile  $message TODO
    
        return_json(0,"交换成功","","/mobile/moneylists/prizemoney");
    }
    

    /*
     * 写交换流水
     */
    protected function _tfmoney_log($my_uid,$my_nickname,$to_uid,$to_nickname,$content,$money,$logtype){
        //写流水
        $myinfo = $this->memberModel->where(array('uid'=>$my_uid))->find();
        $data = array(
            "uid" => $my_uid,
            "nickname" => $my_nickname,
            "content" => $content,
            "logtype" => $logtype,//0支出  1收入
            "mtype" => 12,//1佣金
            "money" => $money,
            "un_lock" => 1,//1解锁 ,0锁定, 现在都为解锁,直接到账
            "create_time" => date("Y-m-d H:i:s"),
            "from_uid" => $this->uid,
            "to_uid" => $to_uid,
            'cash_money' => $myinfo['prize_money'] + $myinfo['lockprize_money']
        );
        $res = $this->moneylogModel->addMoneylog($data);
        
        return $res;
    }
   

    /*
     * 检查并返回收款方的信息
     */
    protected function _getfriend($uid){
        
        //判断是不是手机号码
        $is_mobile = check_mobile($uid);
        if($is_mobile){
            $where = array(
                "mobile" => $uid,
            );
        }else{
            $where = array(
                "uid" => $uid,
            );
        }
        
        $res = $this->memberModel->getMember($where);
        if(empty($res)){
            return_json(1,"未找到对方信息,请检查");
        }
        
        if($res['status'] != 1){
            return_json(1,"对方账户已被禁用或待审核");
        }
        
        if($res['uid'] == $this->uid){
            return_json(1,"你不能给自己转".C('YONGJIN_NAME'));
        }

        return $res;
        
    }
    
    
    /*
     * 根据uid获取用户信息
     */
    public function getfriendajax(){
        $uid = get('uid');
        $res = $this->_getfriend($uid);
        return_json(0,"",$res);
        
    }

    /*
     * 拼接模板消息
     * 佣金转出
     */
    protected function _tfmoney_tmp($log_id,$msg_user,$money,$header){
    
        $tmp_id = $this->tmpl['YUE']['tmp_id'];
		$color = $this->tmpl['YUE']['color'];
    
        $url = get_domain()."/mobile/moneylists/money/?log_id=".$log_id;
        
        $footer ='\\n'."点击查看详情...";
        
        
    
        $msg = array(
            "touser" => $msg_user['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($header),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($msg_user['nickname']),//昵称
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($msg_user['prize_money'] + $msg_user['lockprize_money']),//余额
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//时间
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    /*
     * 通知,模板消息
     * 1
     */
    protected function _tfmoney_msg($log_id,$msg_user,$money,$header){
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$msg_user['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg_json = $this->_tfmoney_tmp($log_id,$msg_user,$money,$header);//拼接模板消息
    
        $msg_data = array(
            "uid" => $msg_user['uid'],
            "openid" => $msg_user['openid'],
            "nickname" => $msg_user['nickname'],
            "groupid" => -1,
            "content" => $msg_json,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
    
        $this->tmpmsgModel->addtmpmsg($msg_data);//添加消息到数据库队列
    
        return true;
    }
    
    
    
    protected function _checkCode($data){
        if(!$data['smscode']) {
            return_json(1,'请输入验证码');
        }
        //检查验证码是否正确
        $codewhere = array(
            "code_id" => $data['code_id'],
            "code" => $data['smscode'],
            "mobile" => $data['mobile'],
        );
        $code_id = $data['code_id'];
        $res = $this->smscodeModel->where($codewhere)->find();
        if(!$res){
            //将尝试次数加1
            $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
            return_json(1,"验证码错误");
        }
        
        if($res['ip'] != $ip){
          //  $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
          //  return_json(1,"你的网络有风险,已阻止此次验证!");
        }
        
        if(strtotime($res['expired_time']) < time()){
            return_json(1,"验证码已过期,请重新获取!");
        }
        
        if($res['try_time'] > 2){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        if($res['status'] != 1){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        //验证通过
        //将验证码作废
        $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
        $this->smscodeModel->where(array("code_id"=>$code_id))->setField('status',0);
        return true;
        
    }
  
    
    
}